<?php
declare (strict_types = 1);


namespace app\admin\middleware;


use http\Client\Response;
use think\facade\View;

class CheckLogin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //登录验证，未登录跳转至登录界面
        if (empty(session('userId')) && $request->baseUrl() != "/admin/index/login") {
            // 跳转至登录页面
            return redirect("/admin/index/login");
        }
        //不需要验证的Url权限
        $notPermissionsUrl = [
            '/admin',
            '/admin/index',
            '/admin/index/index',
            '/admin/index/login',
            '/admin/index/get_login_user',
            '/admin/index/get_basic_tree',
            '/admin/index/logout',
            '/admin/index/lock_screen',
            '/admin/index/theme',
            '/admin/index/note',
            '/admin/index/message',
            '/admin/user/selector',//选择人员案例
        ];
        //权限验证
        if(_current_user('adminType') != 1 && !in_array($request->baseUrl(), $notPermissionsUrl)
        && !in_array($request->baseUrl(), _current_user('permissionsUrl'))){
            if($request->isGet()){
                // 静态资源存储位置
                View::assign("ctxPath", get_config('ctx_path'));
                return view("public/403");
            }else{
                return json(['code'=>403,'data'=>[],'msg'=>'抱歉，你无权操作当前功能！','success'=>false]);
            }

        }

        //todo 服务器权限控制，自己拉去代码之后可以删除
        if($request->isPost() && !in_array($request->baseUrl(), ["/admin/error/post_403","/admin/index/login"])){
            return redirect("/admin/error/post_403");
        }

        return $next($request);
    }

}